<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="报修单号" prop="code" class="repairs">
          <CodeRuleInput :band-value.sync="formData.code" table-name="device_repair_report" column-name="code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="报修设备" class="clickChoose" prop="bookId">
          <el-input v-model="formData.deviceName" placeholder="请选择" readonly />
          <!--          <el-select v-model="formData.bookId" filterable clearable placeholder="请选择">-->
          <!--            <el-option-->
          <!--              v-for="item in deviceOptions"-->
          <!--              :key="item.bookId"-->
          <!--              :label="item.deviceName"-->
          <!--              :value="item.bookId"-->
          <!--            />-->
          <!--          </el-select>-->
          <a class="clickChoose_button" @click.prevent="chooseEquipments">
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="设备状态">
          <DictSelect :band-value.sync="formData.deviceStatusCode" dict-type="state" />
        </el-form-item>
        <el-form-item label="设备故障时间" prop="malfunctionTime">
          <el-date-picker
            v-model="formData.malfunctionTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="报修人员" class="clickChoose" prop="reportPersonName">
          <el-input v-model="formData.reportPersonName" placeholder="请选择" readonly />
          <!--          <el-select v-model="formData.reportPersonId" filterable clearable placeholder="请选择">-->
          <!--            <el-option-->
          <!--              v-for="item in userOptions3"-->
          <!--              :key="item.userId"-->
          <!--              :label="item.realName"-->
          <!--              :value="item.userId"-->
          <!--            />-->
          <!--          </el-select>-->
          <a class="clickChoose_button" @click.prevent="chooseTeam">
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="期望修复时间" prop="expectedTime">
          <el-date-picker
            v-model="formData.expectedTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-divider />
        <el-form-item label="故障类型" class="clickChoose" prop="repairTypeName">
          <el-input v-model="formData.typeName" placeholder="请选择" readonly />
          <!--          <el-select v-model="formData.typeId" filterable clearable placeholder="请选择">-->
          <!--            <el-option-->
          <!--              v-for="item in typeOptions"-->
          <!--              :key="item.id"-->
          <!--              :label="item.name"-->
          <!--              :value="item.id"-->
          <!--            />-->
          <!--          </el-select>-->
          <a class="clickChoose_button" @click.prevent="addType">
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="紧急程度">
          <el-select v-model="formData.emergencyDegree" filterable clearable placeholder="请选择">
            <el-option
              v-for="item in userOptions4"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="故障情况拍照" class="double">
          <FileManageFull
            :file-names="formData.docName"
            :file-real-names="formData.docRealName"
            :file-urls="formData.docUrl"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.fileUrl"
            :row-index="1"
            @fileName="setFileName2"
          />
        </el-form-item>
        <el-form-item label="故障现象" class="double">
          <el-input
            v-model="formData.phenomenon"
            type="textarea"
            maxlength="200"
            show-word-limit
            placeholder="请输入"
          />
        </el-form-item>
        <el-divider />
        <el-form-item label="立即指派" class="appoint">
          <el-switch
            v-model="formData.appoint"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#999999"
          />
        </el-form-item>
        <el-form-item v-if="isRoleSelect" label="维修人员" prop="repairPersonId" class="clickChoose">
          <el-input v-model="formData.repairPersonName" placeholder="请选择" readonly :disabled="!formData.appoint" />
          <a v-if="formData.appoint" class="clickChoose_button" @click.prevent="chooseRoleAndPeople">
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item v-else label="维修人员" prop="repairPersonId" class="clickChoose">
          <el-input v-model="formData.repairPersonName" placeholder="请选择" readonly :disabled="!formData.appoint" />
          <a v-if="formData.appoint" class="clickChoose_button" @click.prevent="chooseTeamAndPeople">
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="计划修复时间范围" prop="planTimeArr" class="double">
          <el-date-picker
            v-model="formData.planTimeArr"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
            placeholder="请选择"
            :editable="false"
            :disabled="!formData.appoint"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="submit">提交</el-button>
    </div>
  </div>
</template>

<script>
import { getSystemSet } from '@/api/common/systemSet'
import { addOrUpdate, getInfo } from '@/api/equipmentManage/equipmentRepair/equipmentReportRepair'
import chooseEquipment from '../../baseInfo/equipmentInfo/chooseEquiment.vue'
import chooseRolePeople from './chooseRolePeople.vue'
import addErrorType from '../errorType/addErrorType'
import chooseTeam from '../../baseInfo/maintenanceTeam/chooseTeam.vue'
import servacePersonnel from './servacePersonnel'
import { mapGetters } from 'vuex'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    typeId: {},
    defaultValue: {}
  },
  data() {
    const validateTime = (rule, value, callback) => {
      this.$refs.form.clearValidate('expectedTime')
      this.$refs.form.clearValidate('planTimeArr')
      if (this.formData.expectedTime < this.formData.malfunctionTime) {
        callback(new Error('设备故障时间不能大于期望修复时间'))
      } else if (this.formData.malfunctionTime > this.formData.planTimeArr) {
        callback(new Error('设备故障时间不能大于计划修复时间范围'))
      } else {
        callback()
      }
    }
    const repairTime = (rule, value, callback) => {
      this.$refs.form.clearValidate('malfunctionTime')
      if (this.formData.malfunctionTime > this.formData.expectedTime) {
        callback(new Error('期望修复时间不能小于设备故障时间'))
      } else {
        callback()
      }
    }
    const planTimeArr = (rule, value, callback) => {
      this.$refs.form.clearValidate('malfunctionTime')
      if (this.formData.planTimeArr < this.formData.malfunctionTime) {
        callback(new Error('计划修复时间范围不能小于设备故障时间'))
      } else if (this.formData.appoint === 1) {
        if (!this.formData.planTimeArr) {
          callback(new Error('计划修复时间范围不能为空'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const repairPersonId = (rule, value, callback) => {
      if (this.formData.appoint === 1) {
        if (!this.formData.repairPersonId) {
          callback(new Error('维修人员不能为空'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        roleIdsArray: undefined,
        roleIds: undefined,
        formData: undefined,
        malfunctionTime: this.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        bookName: undefined,
        deviceStatusLabel: undefined,
        expectedTime: undefined,
        typeName: undefined,
        emergencyDegreeLabel: undefined,
        reportPersonName: undefined,
        phenomenon: undefined,
        repairPersonName: undefined,
        planTime: undefined,
        standingBookId: undefined,
        standingBookName: undefined,
        deviceStatusCode: undefined,
        emergencyDegreeCode: undefined,
        repairPersonId: undefined,
        reportPersonId: undefined,
        repairTypeId: undefined,
        repairTypeName: undefined,
        planTimeArr: undefined,
        typeId: undefined,
        bookId: undefined,
        deviceName: undefined,
        emergencyDegree: undefined,
        checkPersonName: undefined,
        appoint: undefined,
        fileName: '',
        fileUrl: '',
        fileRealName: '',
        docName: '',
        docRealName: '',
        docUrl: '',
        isSubmit: 0,
        status: 1
      },
      rolePeopleInfo: [],
      isRoleSelect: '',
      typeCodeId: '',
      num: 1,
      roleOptions: [],
      typeOptions: [],
      deviceOptions: [],
      userOptions2: [],
      userOptions3: [],
      userOptions4: [
        { id: 0, label: '轻微' },
        { id: 1, label: '重要' },
        { id: 2, label: '紧急' }
      ],
      rules: {
        malfunctionTime: [
          { validator: validateTime, trigger: 'change' }
        ],
        expectedTime: [
          { validator: repairTime, trigger: 'change' }
        ],
        planTimeArr: [
          { required: true, validator: planTimeArr, trigger: 'change' }
        ],
        bookId: [
          { required: true, message: '报修设备不能为空', trigger: 'change' }
        ],
        code: [
          { required: true, message: '报修单号不能为空', trigger: 'blur' }
        ],
        repairPersonId: [
          { required: true, validator: repairPersonId, trigger: 'change' }
        ]
        // planTimeArr: [
        //   { required: true, message: '报修单号不能为空', trigger: 'blur' }
        // ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'userId',
      'userName',
      'companyId'
    ])
  },
  watch: {
    'formData.appoint'() {
      if (this.formData.appoint === 0) {
        this.$refs.form.clearValidate('planTimeArr')
        this.$refs.form.clearValidate('repairPersonId')
      }
    }
  },
  created() {
    if (!this.id) { // 没有id就是新增
      Object.keys(this.defaultValue).forEach(key => { // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
    this.getSystemSet()
    this.formData.reportPersonName = this.userName
    this.formData.reportPersonId = this.userId
    this.typeCodeId = this.typeId
  },
  methods: {
    getSystemSet() {
      // 获取系统设置数据
      getSystemSet(this.companyId).then(res => {
        // 获取系统设置中的维修人员角色筛选
        this.isRoleSelect = res.data.MaintenanceRole
      })
    },
    getInfo() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.formData.roleIdsArray = this.formData.roleIds.split(',')
      })
    },
    submit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.formData.reportPersonName = this.userName
          this.formData.reportPersonId = this.userId
          this.formData.roleIds = this.formData.roleIdsArray
          // this.formData.isSubmit = 1
          this.formData.isSubmit = this.formData.appoint
          addOrUpdate(this.formData).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    chooseTeam() {
      this.$layer.iframe({// 弹框
        content: {
          content: servacePersonnel, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            userId: this.formData.reportPersonId,
            peopleId: this.formData.maintainPersonId ? this.formData.maintainPersonId : ''
          }// props
        },
        area: ['1200px', '600px'],
        title: '选择报修人员', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 选择角色人员
    chooseRoleAndPeople() {
      this.$layer.iframe({// 弹框
        content: {
          content: chooseRolePeople, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.rolePeopleInfo,
            roleId: this.isRoleSelect
          }// props
        },
        area: ['1200px', '600px'],
        title: '选择维修人员', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 选择维保班组和人员
    chooseTeamAndPeople() {
      this.$layer.iframe({// 弹框
        content: {
          content: chooseTeam, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            userId: this.formData.repairPersonId,
            peopleId: this.formData.maintainPersonId ? this.formData.maintainPersonId : ''
          }// props
        },
        area: ['1200px', '600px'],
        title: '选择维修人员', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    //
    showRolePeople(row) {
      console.log(row)
      this.rolePeopleInfo = row
      this.$nextTick(() => {
        this.formData.repairPersonId = row[0].userId
        this.formData.repairPersonName = row[0].realName
      })
      console.log(this.formData)
    },
    // 选择报修人员和班组返回id
    showTeam(teamId, peopleId, row) {
      this.formData.maintenanceId = teamId
      this.$nextTick(() => {
        if (peopleId) {
          this.formData.reportPersonId = row.userId
          this.formData.reportPersonName = row.realName
        }
      })
    },

    // 选择人员和班组返回id
    showTeamAndPeople(teamId, row, peopleId, num) {
      this.formData.maintenanceId = teamId
      this.$nextTick(() => {
        if (peopleId) {
          this.formData.repairPersonId = row.userId
          this.formData.repairPersonName = row.realName
        }
      })
    },
    addType() { // 打开故障类型详情弹窗
      this.$layer.iframe({// 弹框
        content: {
          content: addErrorType, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            typeId: this.formData.typeId ? this.formData.typeId : ''
          }// props
        },
        area: ['700px', '492px'],
        title: '选择故障类型', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    chooseEquipments() {
      this.$layer.iframe({// 弹框
        content: {
          content: chooseEquipment, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            bookId: this.formData.bookId ? this.formData.bookId : ''
          }// props
        },
        area: ['1200px', '600px'],
        title: '选择报修设备', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    addErrorType(row) { // 设备类型弹窗关闭后赋值
      this.formData.typeId = row.id
      this.formData.typeName = row.name
    },
    setFileName(...data) {
      this.formData.docName = data[0]
      this.formData.docRealName = data[1]
      this.formData.docUrl = data[2]
    },
    setFileName2(...data) {
      this.formData.fileName = data[0]
      this.formData.fileRealName = data[1]
      this.formData.fileUrl = data[2]
    },
    // 获取保养设备id
    showEquipment(data) {
      this.formData.bookId = data.id
      this.formData.deviceName = data.code + '/' + data.name
    }
  }
}
</script>

<style lang="less" scoped>
.main_main{
  /deep/ .el-form-item__label{
    width: 150px !important;
  }
  /deep/ .el-form-item__content{
    width: calc(100% - 140px) !important;
  }
  /deep/ .el-range-separator {
    padding-right: 50px;
  }
  /deep/ .appoint {
    width: 700px;
  }
}
</style>
